package org.ws.httphelper.example.openapi;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ws.httphelper.core.pipeline.HandlerOrder;
import org.ws.httphelper.core.pipeline.RequestHandler;
import org.ws.httphelper.exception.RequestException;
import org.ws.httphelper.model.RequestContext;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

@Slf4j
@HandlerOrder(level = HandlerOrder.OrderLevel.USER,value = 1)
public class BuildSnHandler implements RequestHandler {

    @Override
    public boolean handler(RequestContext requestContext) throws RequestException {
        Object input = requestContext.getInput();
        String sk = null;
        if(input instanceof SearchRegionParam) {
            SearchRegionParam searchRegionParam = (SearchRegionParam) input;
            sk = searchRegionParam.getSk();
        }
        else if(input instanceof Map){
            Map map = (Map)input;
            sk = String.valueOf(map.get("sk"));
        }
        if(StringUtils.isBlank(sk)){
            throw new RequestException("sk is blank.");
        }
        long timestamp = System.currentTimeMillis();
        Map<String, Object> params = requestContext.getParams();
        params.put("timestamp",timestamp);
        String url = requestContext.getRequestData().getUrl();
        try {
            URL u = new URL(url);
            String path = u.getPath();
            StringBuilder queryString = new StringBuilder();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                queryString.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"))
                        .append("&");
            }
            queryString.deleteCharAt(queryString.length()-1);
            String wholeStr = path + "?" + queryString.toString() + sk;
            wholeStr = URLEncoder.encode(wholeStr, "UTF-8");
            String sn = getMd5(wholeStr);
            url = url.substring(0, url.lastIndexOf("?")) + "?" + queryString.toString() + "&sn=" + sn;
            log.debug("snurl:{}", url);
            requestContext.getRequestData().setUrl(url);
        }
        catch (UnsupportedEncodingException e){
            throw new RequestException(e.getMessage(),e);
        } catch (MalformedURLException e) {
            throw new RequestException(e.getMessage(),e);
        }
        return true;
    }

    public String getMd5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }
}
